#! C:\Perl\bin\perl.exe

# Copyright (c) 2010, College Center for Library Automation

# See the included Copyright.txt file for full license

# Login once for all colleges. Ask for report for each college.

use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request;
use HTTP::Request::Common;
use Date::Calc qw(Decode_Month Add_Delta_YM Today);
use Text::CSV;

use avsCommon;


my ($content, $response, $request, $url);
my ($viewstate, $eventvalidation);
my ($runyear, $runmonth, $runday);

# create web user agent and cookie jar
my $ua =  new LWP::UserAgent(keep_alive=>1);
$ua->cookie_jar( {} );

dbsetup();

getLogin();

do {
	# setup the date parameters for the loop. 
	if ($begyear == $endyear) {
		($runyear, $runmonth, $runday) = @enddate;	# same year collect to enddate
	}
	else {
		($runyear, $runmonth) = ($begyear, 12);	# previous years collect to december of that year
	};

	# run once for each year covered by beg and end date. typically beg and end month the same.
	while ($runyear <= $endyear) {

		getStats ();

		# advance to the next year. when we hit the end year, set the end month to end year.
		$runyear++;
		$runmonth = $endmonth if ($runyear==$endyear);
	}

} while ($sthlogin->fetch);

dbshutdown();

doLogout();

exit ();

sub getLogin {
	$url = 'http://eadmin.epnet.com/eadmin/Login.aspx';
	$response = $ua->request(GET $url);
	if (!$response->is_success) {
		die "#error:$0: GET login $url : " . $response->status_line;
	};

	$content=$response->decoded_content;
	
	$content =~ /VIEWSTATE\" value\=\"(?<viewstate>.*?)\".*?EVENTVALIDATION\" value\=\"(?<eventvalidation>.*?)\"/sm;
	$viewstate = urlencode($+{viewstate});
	$eventvalidation = urlencode($+{eventvalidation});
	
	# POST login request using viewstate and eventvalidation just returned. sets cookie with session
	$request = HTTP::Request->new(POST => $url);
	$request->content_type('application/x-www-form-urlencoded');
	$request->content("__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=$viewstate" .
			"&UserName=$vendorusername&Password=$vendorpassword&Submit=++Login++&__EVENTVALIDATION=$eventvalidation");
	$response = $ua->request($request);
	
	if (!$response->is_success && substr($response->status_line,0,3) ne '302') {
		die "#error:$0: POST login $url" . $response->status_line;
	};

	# get viewstate and eventvalidation for report form
	$url = 'http://eadmin.epnet.com/eadmin/Reports/SelectReportsForm.aspx';
	$response = $ua->request(GET $url);
	if (!$response->is_success) {
		die "#error:$0: GET form $url : " . $response->status_line;
	};

	$content=$response->decoded_content;
	$content =~ /VIEWSTATE\" value=\"(?<viewstate>.*?)\".*?EVENTVALIDATION\" value=\"(?<eventvalidation>.*?)\"/s;
	$viewstate = urlencode($+{viewstate});
	$eventvalidation = urlencode($+{eventvalidation});

	# post prior to change to counter reports.
	$url = 'http://eadmin.epnet.com/eadmin/Reports/SelectReportsForm.aspx';
	$request = new HTTP::Request POST => $url;
	$request->content_type('application/x-www-form-urlencoded');
	$request->content('__EVENTTARGET=&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=' . $viewstate .
		'&DataChanged=&ConfirmSave=&HyperLinkUrl=%2Feadmin%2FReports%2FSelectCounterReportsForm.aspx&ClearState=&AdminGridKey=&AdminGridCollumn=&AdminGridValue=&AdminGridTitleCtr=&AdminGridTitleCtrValue=&' .
		'AddedAction=&BrowseButton=&AdminGridUpDownButton=&AdminGridCurrentPage=&ConfirmCancel=&reportType=session&scope=consortium&scopeCustId=' . $username .
		"&detail=site&timePeriodFromMonth=$endmonth&timePeriodFromYear=$endyear&timePeriodToMonth=$endmonth&timePeriodToYear=$endyear" .
		'&displayBy=Month&include=n&fields=SessCount&fields=SessDuration&fields=Searches&fields=FullText&fields=PdfFTCount&fields=HtmlFTCount&fields=ImageCount&' .
		'fields=SmartLinkCount&fields=CustomLinkCount&fields=AbstractCount&sort=default_sort_order&reportFormat=html&pageLines=25&uf1=alluse&uf2=alluse&database=&' .
		'intface=&collection=&epConsSite=&whoami=session&hideUf=&__EVENTVALIDATION=' . $eventvalidation );
	$response = $ua->request($request);
	
	# get viewstate and eventvalidation for counter report form
	$url = 'http://eadmin.epnet.com/eadmin/Reports/SelectCounterReportsForm.aspx';
	$response = $ua->request(GET $url);
	if (!$response->is_success) {
		die "#error:$0: GET form $url : " . $response->status_line;
	};

	$content=$response->decoded_content;
	$content =~ /VIEWSTATE\" value=\"(?<viewstate>.*?)\".*?EVENTVALIDATION\" value=\"(?<eventvalidation>.*?)\"/s;
	$viewstate = urlencode($+{viewstate});
	$eventvalidation = urlencode($+{eventvalidation});

};

sub getStats {
	# post the report form request 
	$url = 'http://eadmin.epnet.com/eadmin/Reports/SelectCounterReportsForm.aspx';
	$request = new HTTP::Request POST => $url;
	$request->content_type('application/x-www-form-urlencoded');
	$request->content('__EVENTTARGET=saveReportButton&__EVENTARGUMENT=Save+Report&__LASTFOCUS=&__VIEWSTATE=' . $viewstate .
		'&DataChanged=&ConfirmSave=&HyperLinkUrl=&ClearState=&AdminGridKey=&AdminGridCollumn=&AdminGridValue=&AdminGridTitleCtr=&AdminGridTitleCtrValue=&AddedAction=&BrowseButton=&AdminGridUpDownButton=&AdminGridCurrentPage=&ConfirmCancel=&reportType=cntrdb1&scope=site&scopeCustId=' . $username .	
		"&database=allsub&timePeriodFromMonth=$runmonth&timePeriodFromYear=$runyear&timePeriodToMonth=$runmonth&timePeriodToYear=$runyear&pageLines=500&reportFormat=csv&collection=&whoami=cntrdb1&__EVENTVALIDATION=$eventvalidation");
	$response = $ua->request($request);

	if (!$response->is_success && substr($response->status_line, 0, 3) ne '302') {
		die "#error:$0: POST report failed $url : " . $response->status_line;
	};

	$content=$response->decoded_content;

	# save contents for possible debugging
	savecontent('Ebsco', "$collegeid", $content);

	my @contents = split ("\r\n", $content);

	my $datasource;

	# grab the dates off of the header lines, first four columns are not dates
	my @periods = ('','','','');	
	my $begperiod = myperiod($begyear, $begmonth);
	my $endperiod = myperiod($endyear, $endmonth);
	my $begperiodndx = 4;
	my $endperiodndx = 4;

	while ($contents[1] =~ /(?<month>\w+)-(?<year>\d{4})/g) {
		my $period = myperiod($+{year},$+{month});
		$begperiodndx++ if ($period lt $begperiod);
		$endperiodndx++ if ($period lt $endperiod);
		push @periods, $period;
	}
	$begperiodndx-- if $begperiodndx == 16;	# prevent multiyear problem
	$endperiodndx-- if $endperiodndx == 16;	# prevent multiyear problem

	my @sessions=(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
	my @searches=(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);

	my $csv = Text::CSV->new({binary => 1});

	# parse each csv line, start with ~line 2 to 1 before the end
	foreach my $content (@contents[2..$#contents]) {

		# ignore blank lines
		if (! $content) {
			next;
		};

		#parse the line
		if ($csv->parse($content)) {
			my @columns = $csv->fields();

			# row of blank data seperates the lines of data. report previous two lines
			if ($columns[0] eq ' ') {
				foreach my $i ($begperiodndx..$endperiodndx) {
					print "$vendorid $collegeid $periods[$i] $datasource $sessions[$i] $searches[$i]\n";
					$sthstats->execute($vendorid, $collegeid, $datasource, $periods[$i], $sessions[$i], 1)
						or die '#error: sthstats execute 1 failed';
					$sthstats->execute($vendorid, $collegeid, $datasource, $periods[$i], $searches[$i], 2)
						or die '#error: sthstats execute 2 failed';
				};
				@sessions=(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
				@searches=(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
				next;
			}

			# data line is either session or searches. save information appropriately
			$datasource = $columns[0];
			if ($columns[3] =~/sessions/i) {
				@sessions = @columns;
			}
			elsif ($columns[3] =~/searches/i) {
				@searches = @columns;
			}
			else {
				print "#error: expected sessions or searches, found: $columns[3]\n";
			}
		}

		else {
			my $err = $csv->error_input;
			print "#error:$0: csv parse error : $err\n";
		}
	}
}

sub doLogout {

	# get viewstate and eventvalidation for report form
	$url = 'http://eadmin.epnet.com/eadmin/Logout.aspx';
	$response = $ua->request(GET $url);
}